﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace MvcBase
{
    public class DbContextRepository<T> : BaseRepository where T :  DbContext
    {
        #region Fields

        private T _context;
        private Type _contextType;

        #endregion

        #region Properties

        public T Context
        {
            get
            {
                if (_context == null)
                    _context = Activator.CreateInstance<T>();

                return _context;
            }
        }

        #endregion

        #region Methods

        public override void Insert<E>(E entity)
        {
            Context.Set<E>().Add(entity);
        }

        public override void Update<E>(E entity)
        {
            Context.Set<E>().Attach(entity);
            Context.Entry<E>(entity).State = EntityState.Modified;
        }

        public override void Delete<E>(E entity)
        {
            Context.Set<E>().Attach(entity);
            Context.Entry<E>(entity).State = EntityState.Deleted;
        }

        public override int SaveChanges(bool validateEntities)
        {
            if (Context.Database.Connection.State != ConnectionState.Open)
                throw new Exception("The database is currently not online.");
            Context.Configuration.ValidateOnSaveEnabled = validateEntities;
            return Context.SaveChanges();
        }

        public override IQueryable<E> Select<E>()
        {
            if (Context.Database.Connection.State != ConnectionState.Open)
                throw new Exception("The database is currently not online.");

            return Context.Set<E>();
        }

        public override E Select<E>(object key)
        {
            if (Context.Database.Connection.State!=ConnectionState.Open)
                throw new Exception("The database is currently not online.");

            return Context.Set<E>().Find(key);
        }

        public override void Dispose()
        {
            if (Context != null)
                Context.Dispose();
        }

        #endregion
    }
}
